package com.itheima.controller;

import com.itheima.domain.Role;
import com.itheima.domain.User;
import com.itheima.service.RoleService;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @RequestMapping("/list")
    public ModelAndView list(){
        ModelAndView modelAndView = new ModelAndView();
        List<User> userList =  userService.list();
        modelAndView.addObject("userList",userList);
        modelAndView.setViewName("user-list");
        return modelAndView;
    }

    @RequestMapping("/saveUI")
    public ModelAndView saveUI(){
        ModelAndView modelAndView = new ModelAndView();
        List<Role> roleList = roleService.list();
        modelAndView.addObject("roleList",roleList);
        modelAndView.setViewName("user-add");
        return modelAndView;
    }

    @RequestMapping("/save")
    public String save(User user,Long[] roleIds){

        userService.save(user,roleIds);

        return "redirect:/user/list" ;
    }

    @RequestMapping("/del/{uid}")
    public String del(@PathVariable("uid") Long uid){

        userService.del(uid);

        return "redirect:/user/list" ;
    }

    @RequestMapping("/login")
    public String login(String username, String password, HttpSession session){
        System.out.println(username);
        System.out.println(password);
        //登录页面并且把数据存入到session中
       User user =  userService.login(username,password);

        System.out.println(user);

       if(user != null){//登录成功，跳转到首页
           session.setAttribute("user",user);
           return "redirect:/index.jsp" ;
       }
       //登录失败，跳转回登录页面
        return "redirect:/login.jsp" ;
    }


}
